import { defineStore } from 'pinia'
import request from '@/utils/request'
import { ApiRes, categoryItem, SubCategory, TOpCategory } from '@/types/data'
import { topCategory } from '../constants'

const defaultCategory = topCategory.map(item => ({name:item}))

// interface ApiRes<T> {
//   code: string
//   msg: string
//   result: T[]
// }

// interface categoryItem {
//   id: string,
//   name: string
//   picture: string
// }

export default defineStore('category', {
  state() {
      return {
        list: defaultCategory as categoryItem[],
        topCategory: {} as TOpCategory,
        subCategory: {} as SubCategory
      }
  },
  actions: {
    async getAllCategory() {
      const res = await request.get<ApiRes<categoryItem[]>>('/home/category/head')
      // console.log(res.data.result)
      res.data.result.forEach(item => item.open = false)
      this.list = res.data.result
    },
    show(id:string) {
      const item =  this.list.find(item => item.id === id)
      // item && (item.open = true)
      item!.open = true
    },
    hide(id:string) {
      const item = this.list.find(item => item.id === id)
      item!.open = false
    },
    async getTopCategory(id:string) {
      const res = await request.get<ApiRes<TOpCategory>>('/category', {
        params: {
          id
        }
      })
      // console.log(res)
      this.topCategory = res.data.result
      
    },
    async getSubCategory(id:string) {
      const res = await request.get<ApiRes<SubCategory>>('/category/sub/filter', {
        params: {
          id
        }
      })
      this.subCategory = res.data.result
    },
    resetCategory() {
      this.subCategory = {} as SubCategory
    }
  }
})